package internal.generator;

import java.util.Map;
import java.util.regex.Matcher;

import org.lightcommons.util.PatternMap;
import org.lightcommons.util.StringUtils;
import org.lightcommons.util.PatternMap.MatchedResult;

public class FileMapping {
	private PatternMap<String> patternMap;

	public void setPatternMap(PatternMap<String> patternMap) {
		this.patternMap = patternMap;
	}
	
	public String getTargetFileName(String relativePath,String outputRoot,Map<String, Object> context){
		String path = StringUtils.cleanPath(relativePath);
		if(patternMap!=null){
			MatchedResult<String> matchedResult = patternMap.matcher(path);
				if(matchedResult!=null){
				path = matchedResult.getResult();
				if("%null".equals(path))
					return null;
				Matcher matcher = matchedResult.getMatcher();
				for(int i=0;i<=matcher.groupCount();i++){
					path = StringUtils.replace(path, "%"+i, matcher.group(i));
				}
			}
		}
		path = FileHelper.cleanFileName(path);
		path= outputRoot +"/"+new StringTemplate(path,context).toString();
		
		return StringUtils.cleanPath(path);
	}

}
